package com.bulletelc.apollopre.module.main.center.setting;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.constants.SPKey;
import com.bulletelc.apollopre.entity.SettingBean;
import com.bulletelc.apollopre.framework.BaseActivity;
import com.bulletelc.apollopre.interfaces.listener.PermissionListener;
import com.bulletelc.apollopre.module.main.center.setting.activity.ModifyProfileActivity;
import com.bulletelc.apollopre.module.main.center.setting.activity.SmsVerifyActivity;
import com.bulletelc.apollopre.module.user.LoginMainActivity;
import com.bulletelc.apollopre.utils.SharedPreferencesUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.bulletelc.apollopre.widget.FoolBar;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by CX on 2018/1/15.
 * 设置界面
 */

public class SettingActivity extends BaseActivity implements View.OnClickListener, FoolBar.ClickCallback,
        PermissionListener, SettingAdapter.onCheckPermissionListener {

    // data
    private String versionName = "";
    private SettingAdapter adapter;
    private List<SettingBean> settingBeans;

    // views
    private ListView listView;
    private Button btnLogout;
    private FoolBar flBar;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnLogout:
                logout();
                break;
        }
    }

    private void logout() {
//        SharedPreferencesUtil.putBoolean(MyApplication.getInstance(), SPKey.SP_CHECK_ISLOAD_AVATAR, true);
        SharedPreferencesUtil.remove(this, SPKey.SP_ACCESS_TOKEN);
        SharedPreferencesUtil.remove(this, SPKey.SP_CHECK_IS_LOGIN);
        MyApplication.setToken(null);
        Intent intent = new Intent(this, LoginMainActivity.class);
        intent.putExtra(IntentCode.EXTRA_KEY_IS_GO_TO_HOME_FRAGMENT,true);
        startActivity(intent);
        finish();
    }

    @Override
    public int getLayoutRes() {
        return R.layout.setting_list_activity;
    }

    @Override
    public void assignViews() {
        listView = findViewById(R.id.lv_setting);
        btnLogout = findViewById(R.id.btnLogout);
        flBar = findViewById(R.id.flBar);
        flBar.setTitle(this.getResources().getString(R.string.center_setting));
    }

    @Override
    public void setListener() {
        btnLogout.setOnClickListener(this);
        flBar.setClickCallback(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        try {
            getVersionName();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        settingBeans = new ArrayList<>();
        settingBeans.add(new SettingBean("更换手机", SmsVerifyActivity.class, GlobalConfig.MSM_ACTION_MODIFY_MOBILE));
        settingBeans.add(new SettingBean("更改密码", SmsVerifyActivity.class, GlobalConfig.MSM_ACTION_MODIFY_PASSWORD));
        settingBeans.add(new SettingBean("修改个人信息", ModifyProfileActivity.class, GlobalConfig.SETTING_MODIFY_INFO));
        settingBeans.add(new SettingBean("清理缓存", GlobalConfig.SETTING_CLEAR_CACHE));
        settingBeans.add(new SettingBean("检查更新" + versionName, GlobalConfig.SETTING_CHECK_VERSION));
        adapter = new SettingAdapter(this, settingBeans);
        listView.setAdapter(adapter);
        adapter.setOnCheckPermissionListener(this);
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onGranted() {
        checkUpdate();
    }

    @Override
    public void onDenied(List<String> deniedPermissions) {

    }

    @Override
    public void check() {
        requestRuntimePermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, SettingActivity.this);
    }

    /**
     * 蒲公英的更新
     */
    private void checkUpdate() {
        PgyUpdateManager.register(SettingActivity.this,
                new UpdateManagerListener() {
                    @Override
                    public void onUpdateAvailable(final String result) {
                        // 将新版本信息封装到AppBean中
                        final AppBean appBean = getAppBeanFromString(result);
                        final AlertDialog.Builder updateDialog = new AlertDialog.Builder(SettingActivity.this);
                        updateDialog.setTitle("发现新版本，是否现在更新？")
                                .setMessage(appBean.getReleaseNote())
                                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        startDownloadTask(
                                                SettingActivity.this,
                                                appBean.getDownloadURL());
                                    }
                                });
                        updateDialog.show();

                    }

                    @Override
                    public void onNoUpdateAvailable() {
                        ToastUtil.showShortToast(getApplicationContext(), "当前是最新版本了");
                    }
                });

    }

    /**
     * 获取版本号
     */
    private void getVersionName() throws PackageManager.NameNotFoundException {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageManager()获取当前类包名，0代表获取版本信息
        PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
        versionName = "(当前版本：" + packageInfo.versionName + ")";
    }

}
